package com.hikvision.open.app.ui.broadcast

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.hikvision.hatomplayer.BroadcastClient
import com.hikvision.hatomplayer.PlayCallback
import com.hikvision.hatomplayer.core.*
import com.hikvision.open.app.model.PlayResult
import com.hikvision.open.app.utils.launchOnUI
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*

/**
 * <p> 广播ViewModel </p>
 * @author 段自航 2021/7/15 15:43
 * @version V1.0
 */
class BroadcastViewModel : ViewModel(), PlayCallback.BroadcastCallback {

    /**
     * 广播结果
     */
    private val _broadcastResult = MutableLiveData<PlayResult>()
    val broadcastResult: LiveData<PlayResult> = _broadcastResult

    /**
     * 广播客户端
     */
    private val broadcastClient: BroadcastClient by lazy {
        BroadcastClient()
    }


    /**
     * 开启广播
     */
    fun startBroadcast(url: String, indexCodes: List<String>) {
        launchOnUI {
            broadcastClient.setBroadcastStatusCallback(this@BroadcastViewModel)
            withContext(Dispatchers.IO) {
                broadcastClient.addBroadcastDataSource(url, indexCodes, null)
                broadcastClient.startBroadcast()
            }
        }
    }

    /**
     * 关闭广播
     */
    fun stopBroadcast() {
        launchOnUI {
            withContext(Dispatchers.IO) {
                broadcastClient.stopBroadcast()
            }
        }
    }

    override fun onBroadcastStatus(
        status: PlayCallback.Status,
        errorCode: String?,
        errorData: String?
    ) {
        when (status) {
            PlayCallback.Status.SUCCESS -> {
                //广播成功
                _broadcastResult.postValue(PlayResult(status = PlayCallback.Status.SUCCESS))
            }
            PlayCallback.Status.FAILED -> {
                //广播失败，先关闭广播
                stopBroadcast()
                _broadcastResult.postValue(
                    PlayResult(
                        status = PlayCallback.Status.FAILED,
                        errorCode = errorCode ?: "-1"
                    )
                )
            }
            PlayCallback.Status.EXCEPTION -> {
                _broadcastResult.postValue(
                    PlayResult(
                        status = PlayCallback.Status.EXCEPTION,
                        errorCode = errorCode ?: "-1"
                    )
                )
            }
            PlayCallback.Status.FINISH -> {
                //什么也不做，因为不会回调这个
            }
        }
    }


}